<template>
    <el-card>
      <!-- 检索表单 -->
      <el-form :inline="true" :model="searchForm" class="mb-2">
        <el-form-item label="货品">
          <el-input v-model="searchForm.goods" placeholder="请输入名称/编码" />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择">
            <el-option v-for="item in productTypes" :key="item.itemTypeId" :label="item.itemTypeName" :value="item.itemTypeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="searchForm.unit" placeholder="请选择">
            <el-option v-for="item in units" :key="item.id || item.unitId" :label="item.unitName || item.name" :value="item.id || item.unitId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 统计卡片 -->
      <div style="display: flex; gap: 16px; margin-bottom: 16px;">
        <el-card style="flex:1; text-align:center;">
          <div style="font-size: 28px;">{{ stats.qty }}</div>
          <div>当前库存数量</div>
        </el-card>
        <el-card style="flex:1; text-align:center;">
          <div style="font-size: 28px;">{{ stats.amount }}</div>
          <div>当前库存金额</div>
        </el-card>
        <el-card style="flex:1; text-align:center;">
          <div style="font-size: 28px; color: green;">{{ stats.inQty }}</div>
          <div>入库数量</div>
        </el-card>
        <el-card style="flex:1; text-align:center;">
          <div style="font-size: 28px; color: orange;">{{ stats.outQty }}</div>
          <div>出库数量</div>
        </el-card>
      </div>
      <!-- 操作按钮 -->
      <div style="margin-bottom: 12px;">
        <el-button type="primary" @click="addItem">添加</el-button>
        <el-button type="success" @click="exportCSV">导出</el-button>
        <el-button @click="resetForm">刷新</el-button>
      </div>
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="itemId" label="货品编号" />
        <el-table-column prop="itemName" label="货品名称" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ scope.row.status === 0 ? '启用' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column prop="itemTypeName" label="货品类型" />
        <el-table-column prop="itemSpec" label="规格型号" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="barcode" label="条码" />
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="locationName" label="库位名称" />
        <el-table-column prop="currentInventory" label="当前库存" />
        <el-table-column prop="inventoryAmount" label="库存金额" />
        <el-table-column prop="inboundQuantity" label="入库数量" />
        <el-table-column prop="outboundQuantity" label="出库数量" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editItem(scope.row)">修改</el-button>
            <el-link type="primary" @click="showInOut(scope.row)">出入库流水</el-link> 
            <el-link type="success" @click="showDistribution(scope.row)">库存分布</el-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
        <pre>{{ dialogContent }}</pre>
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
      <!-- 添加/编辑货品弹窗 -->
      <el-dialog v-model="itemDialogVisible" :title="itemDialogTitle" width="600px">
        <el-form :model="itemForm" :rules="itemFormRules" ref="itemFormRef" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="货品编号" prop="itemId">
                <el-input v-model="itemForm.itemId" :disabled="isEdit" placeholder="系统自动生成" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货品名称" prop="itemName">
                <el-input v-model="itemForm.itemName" placeholder="请输入货品名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="itemForm.status" placeholder="请选择状态">
                  <el-option label="启用" :value="0" />
                  <el-option label="停用" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货品类型" prop="itemTypeId">
                <el-select v-model="itemForm.itemTypeId" placeholder="请选择货品类型" @change="onItemTypeChange">
                  <el-option v-for="item in productTypes" :key="item.itemTypeId" :label="item.itemTypeName" :value="item.itemTypeId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格型号" prop="itemSpec">
                <el-input v-model="itemForm.itemSpec" placeholder="请输入规格型号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="unitId">
                <el-select v-model="itemForm.unitId" placeholder="请选择单位">
                  <el-option v-for="item in units" :key="item.id || item.unitId" :label="item.unitName || item.name" :value="item.id || item.unitId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="条码" prop="barcode">
                <el-input v-model="itemForm.barcode" placeholder="请输入条码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库" prop="warehouseName">
                <el-select v-model="itemForm.warehouseName" placeholder="请选择仓库（可选）" @change="onWarehouseChange" clearable>
                  <el-option v-for="item in warehouses" :key="item.id" :label="item.warehouseName" :value="item.warehouseName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>       
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库位" prop="locationName">
                <el-select 
                  v-model="itemForm.locationName" 
                  placeholder="请选择库位（可选）" 
                  :loading="locationLoading"
                  @change="onLocationChange"
                  clearable
                  filterable
                >
                  <el-option 
                    v-for="item in locations" 
                    :key="item.id || item.locationId" 
                    :label="item.locationName" 
                    :value="item.locationName"
                  />
                  <el-option v-if="locations.length === 0 && !locationLoading" label="暂无库位数据" value="" disabled />
                  <el-option v-if="locationLoading" label="正在加载库位..." value="" disabled />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购价" prop="purchasePrice">
                <el-input-number v-model="itemForm.purchasePrice" :precision="2" :step="0.01" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="销售价" prop="outboundPrice">
                <el-input-number v-model="itemForm.outboundPrice" :precision="2" :step="0.01" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="cancelItem">取消</el-button>
          <el-button type="primary" @click="saveItem" :loading="saveLoading">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { useRouter } from 'vue-router'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'

  const router = useRouter()

  const searchForm = ref({
    goods: '',
    goodsType: '',
    unit: ''
  })

  const stats = ref({ qty: 0, amount: 0, inQty: 0, outQty: 0 })
  const tableData = ref([])
  const loading = ref(false)

  const productTypes = ref([])
  const units = ref([])
  const warehouses = ref([])
  const locations = ref([])
  const locationLoading = ref(false) // 新增：库位加载状态

  async function fetchProductTypes() {
    try {
      console.log('正在获取货品类型...')
      const { data } = await axios.get('/api/goods-management/item-types')
      console.log('货品类型接口返回:', data)
      productTypes.value = data?.items || []
    } catch (error) {
      console.error('获取货品类型失败:', error)
      ElMessage.error('获取货品类型失败')
    }
  }

  async function fetchUnits() {
    try {
      console.log('正在获取单位...')
      const { data } = await axios.get('/api/goods-management/units')
      console.log('单位接口返回:', data)
      units.value = data?.pageData || []
    } catch (error) {
      console.error('获取单位失败:', error)
      ElMessage.error('获取单位失败')
    }
  }

  async function fetchWarehouses() {
    try {
      console.log('正在获取仓库...')
      const { data } = await axios.get('/api/goods-management/warehouses')
      console.log('仓库接口返回:', data)
      warehouses.value = data?.items || []
    } catch (error) {
      console.error('获取仓库失败:', error)
      ElMessage.error('获取仓库失败')
    }
  }

  async function fetchLocations() {
    try {
      console.log('正在获取所有库位数据...')
      locationLoading.value = true
      const { data } = await axios.get('/api/goods-management/locations')
      console.log('库位接口返回:', data)
      locations.value = data?.items || data?.pageData || []
    } catch (error) {
      console.error('获取库位失败:', error)
      ElMessage.error('获取库位失败')
      locations.value = []
    } finally {
      locationLoading.value = false
    }
  }

  // 根据仓库名称获取仓库ID（保留以备后用）
  function getWarehouseId(warehouseName) {
    const warehouse = warehouses.value.find(w => w.warehouseName === warehouseName)
    return warehouse?.id || warehouse?.warehouseId
  }

  // 仓库选择变化时触发（简化版）
  function onWarehouseChange(warehouseName) {
    console.log('仓库选择变化:', warehouseName)
    // 不再清空库位选择，保持独立
  }
  // 库位选择变化时触发（简化版）
  function onLocationChange(locationName) {
    console.log('库位选择变化:', locationName)
    // 可以在这里添加库位相关的逻辑
  }

  // 获取所有库位数据（用于初始化）
  async function fetchAllLocations() {
    try {
      console.log('正在获取所有库位数据...')
      const { data } = await axios.get('/api/goods-management/locations')
      console.log('所有库位接口返回:', data)
      // 这里可以根据需要处理所有库位数据
    } catch (error) {
      console.error('获取所有库位失败:', error)
    }
  }

  // 获取台账数据
  async function fetchData() {
    loading.value = true
    try {
      console.log('正在获取货品列表...')
      const { data } = await axios.post('/api/goods-management/goods-list', {
        goods: searchForm.value.goods,
        goodsType: searchForm.value.goodsType,
        unit: searchForm.value.unit
      })
      console.log('货品列表接口返回:', data)
      // 根据后端返回的数据结构，直接使用数组
      tableData.value = Array.isArray(data) ? data : (data?.pageData || [])
      await fetchStatistics()
    } catch (error) {
      console.error('获取货品列表失败:', error)
      ElMessage.error('获取货品列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  async function fetchStatistics() {
    try {
      console.log('正在获取统计数据...')
      const { data } = await axios.get('/api/goods-management/inventory-summary')
      console.log('统计数据接口返回:', data)
      stats.value = {
        qty: data?.currentInventoryQuantity || 0,
        amount: data?.currentInventoryAmount || 0,
        inQty: data?.inboundQuantity || 0,
        outQty: data?.outboundQuantity || 0
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
    }
  }

  function resetForm() {
    searchForm.value = { goods: '', goodsType: '', unit: '' }
    fetchData()
  }

  // 导出功能
  async function exportCSV() {
    try {
      const res = await axios.post('/api/goods-management/export', {
        goods: searchForm.value.goods,
        goodsType: searchForm.value.goodsType,
        unit: searchForm.value.unit
      }, { responseType: 'blob' })
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', '库存台账.csv')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch (e) {
      // 可加错误提示
    }
  }

  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const dialogContent = ref('')

  // 添加/编辑弹窗相关
  const itemDialogVisible = ref(false)
  const itemDialogTitle = ref('')
  const itemForm = ref({
    itemId: '',
    itemName: '',
    status: 0,
    itemTypeId: '',
    itemSpec: '',
    unitId: '',
    barcode: '',
    warehouseName: '',
    locationName: '',
    purchasePrice: 0,
    outboundPrice: 0
  })
  const isEdit = ref(false)
  const itemFormRef = ref(null)
  const saveLoading = ref(false)

  const itemFormRules = {
    itemId: [{ required: true, message: '请输入货品编号', trigger: 'blur' }],
    itemName: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    itemTypeId: [{ required: true, message: '请选择货品类型', trigger: 'change' }],
    unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
    purchasePrice: [{ required: true, message: '请输入采购价', trigger: 'blur' }],
    outboundPrice: [{ required: true, message: '请输入销售价', trigger: 'blur' }]
  }

  // 添加货品
  function addItem() {
    isEdit.value = false
    itemDialogTitle.value = '添加货品'
    // 自动生成货品编号
    const maxId = Math.max(...tableData.value.map(item => parseInt(item.itemId) || 0), 0)
    itemForm.value = {
      itemId: (maxId + 1).toString(),
      itemName: '',
      status: 0,
      itemTypeId: '',
      itemSpec: '',
      unitId: '',
      barcode: '',
      warehouseName: '',
      locationName: '',
      purchasePrice: 0,
      outboundPrice: 0
    }
    itemDialogVisible.value = true
    nextTick(() => {
      itemFormRef.value?.resetFields()
    })
  }

  // 修改货品
  function editItem(row) {
    isEdit.value = true
    itemDialogTitle.value = '修改货品'
    console.log('修改货品数据:', row)
    
    // 确保所有必要字段都存在
    itemForm.value = {
      id: row.id, // 确保ID字段存在
      itemId: row.itemId || '',
      itemName: row.itemName || '',
      status: row.status || 0,
      itemTypeId: row.itemTypeId || '',
      itemSpec: row.itemSpec || '',
      unitId: row.unitId || '',
      barcode: row.barcode || '',
      warehouseName: row.warehouseName || '',
      locationName: row.locationName || '',
      purchasePrice: row.purchasePrice || 0,
      outboundPrice: row.outboundPrice || 0
    }
    
    console.log('设置的表单数据:', itemForm.value)
    itemDialogVisible.value = true
    nextTick(() => {
      itemFormRef.value?.resetFields()
    })
  }

  // 保存货品
  async function saveItem() {
    if (!itemFormRef.value) return
    await itemFormRef.value.validate((valid) => {
      if (valid) {
        saveLoading.value = true
        const requestData = {
          itemId: itemForm.value.itemId,
          itemName: itemForm.value.itemName,
          itemTypeId: itemForm.value.itemTypeId.toString(),
          itemSpec: itemForm.value.itemSpec,
          unitId: itemForm.value.unitId.toString(),
          entId: "1", // 企业ID，根据实际情况设置
          clientId: "1", // 客户ID，根据实际情况设置
          purchasePrice: parseFloat(itemForm.value.purchasePrice) || 0,
          outboundPrice: parseFloat(itemForm.value.outboundPrice) || 0,
          status: parseInt(itemForm.value.status)
        }
        
        if (isEdit.value) {
          // 修改 - 使用新接口
          const itemId = itemForm.value.id
          if (!itemId) {
            ElMessage.error('货品ID不存在，无法修改')
            saveLoading.value = false
            return
          }
          const updateData = {
            id: itemForm.value.id,
            itemId: itemForm.value.itemId,
            itemName: itemForm.value.itemName,
            itemTypeId: itemForm.value.itemTypeId.toString(),
            itemSpec: itemForm.value.itemSpec,
            unitId: itemForm.value.unitId.toString(),
            entId: "1", // 企业ID，根据实际情况设置
            clientId: "1", // 客户ID，根据实际情况设置
            purchasePrice: parseFloat(itemForm.value.purchasePrice) || 0,
            outboundPrice: parseFloat(itemForm.value.outboundPrice) || 0,
            status: parseInt(itemForm.value.status)
          }
          axios.put('/api/goods-management/update', updateData)
            .then(async res => {
              ElMessage.success('修改成功')
              itemDialogVisible.value = false
              fetchData() // 刷新数据
            })
            .catch(error => {
              console.error('修改失败:', error)
              ElMessage.error('修改失败: ' + (error.response?.data?.message || error.message))
            })
            .finally(() => {
              saveLoading.value = false
            })
        } else {
          // 添加 - 使用正确的接口路径
          axios.post('/api/goods-management/add', requestData)
            .then(async res => {
              ElMessage.success('添加成功')
              itemDialogVisible.value = false
              fetchData() // 刷新数据
            })
            .catch(error => {
              console.error('添加失败:', error)
              ElMessage.error('添加失败: ' + (error.response?.data?.message || error.message))
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
      }
    })
  }

  function cancelItem() {
    itemDialogVisible.value = false
    itemFormRef.value?.resetFields()
  }

  function onItemTypeChange() {
    itemForm.value.itemSpec = '' // 清空规格型号
    itemForm.value.unitId = '' // 清空单位
    itemForm.value.warehouseName = '' // 清空仓库
    itemForm.value.locationName = '' // 清空库位
    itemForm.value.purchasePrice = 0 // 清空采购价
    itemForm.value.outboundPrice = 0 // 清空销售价
  }

  function showInOut(row) {
    dialogTitle.value = '出入库流水 - ' + row.itemName
    dialogContent.value = `货品编号: ${row.itemId}\n本月入库: ${row.inboundQuantity ?? '-'}\n本月出库: ${row.outboundQuantity ?? '-'}`
    dialogVisible.value = true
  }

  function showDistribution(row) {
    // 跳转到库存分布页面，传递货品ID
    router.push({
      name: 'inventoryStatistics',
      query: { 
        itemId: row.itemId,
        itemName: row.itemName,
        itemType: row.itemTypeName,
        itemSpec: row.itemSpec,
        unitName: row.unitName
      }
    })
  }

  // 页面加载时自动拉取数据
  onMounted(() => {
    fetchProductTypes()
    fetchUnits()
    fetchWarehouses()
    fetchLocations() // 获取所有库位数据
    fetchData()
  })
  </script>